package com.imti.httpdemo;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonUtil
{
    private static Gson sGson = new Gson();

    public static CityModel[] parseCityListByGson(String jsonStr)
    {
        Type type = new TypeToken<WeatherResponseObj<CityModel>>(){}.getType();

        WeatherResponseObj<CityModel> result = sGson.fromJson(jsonStr,type);

        return result.getResult();
    }

    public static List<CityModel> parseCityList(String jsonStr) throws JSONException
    {
        List<CityModel> cityList = new ArrayList<>();

        //Json标准解析遵循原则为，由内到外，层层解析
        JSONObject resultObj = new JSONObject(jsonStr);

        //判断字段是否存在
        if (resultObj.has("result"))
        {
            //获取JSON数组
            JSONArray result = resultObj.getJSONArray("result");

            //遍历JsonArray
            for (int i = 0; i < result.length(); i++)
            {
                JSONObject city = result.getJSONObject(i);

                CityModel model = new CityModel();

                if (city.has("id"))
                {
                    model.setId(city.getString("id"));
                }
                if (city.has("province"))
                {
                    model.setProvince(city.getString("province"));
                }
                if (city.has("city"))
                {
                    model.setCity(city.getString("city"));
                }
                if (city.has("district"))
                {
                    model.setDistrict(city.getString("district"));
                }

                cityList.add(model);
            }
        }

        return cityList;
    }
}
